<?php
/**
 * The login controller 
 * 
 * @author Youssef Driouach
 *
 * 20 août 2012
 */
class LoginController extends Zend_Controller_Action{
	/**
	 * initilize the login controller with a specifique title.
	 * 
	 * @see Zend_Controller_Action::init()
	 */
	public function init() {
		$title ="Log in to our web site";
		$this->view->__set("headtitle", $title);
		
		$this->view->headLink()->prependStylesheet("//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css");
	    
	  }
	 
	  
	 
	  public function indexAction() {
	  	
	  	if(Zend_Auth::getInstance()->hasIdentity()){
	  		$this->_redirect('index');
	  	}
	  	
	   	$form = new Application_Form_Login ('loginform');
	    $this->view->form = $form;
	 
	    if ($this->_request->isPost()) {
	      $formData = $this->_request->getPost();
	      if ($form->isValid($formData) AND $form->getElement("submit")->getAttrib("test") == "") {
	        $email = $form->getValue('email');
	        $password = $form->getValue('password');
	        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter());
	        $authAdapter->setTableName('user')
				        ->setIdentityColumn('email')
				        ->setCredentialColumn('password')
				        ->setCredentialTreatment('SHA1(?) AND status = 1')
				        ->setIdentity($email)
				        ->setCredential($password);
	        
	        // try to authenticate a user
	        $result = $authAdapter->authenticate();
	        $this->view->alertType = "error";
	        // is the user valid one?
	        switch ($result->getCode()) {
	        
	        	case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
	        		$this->view->alert = 'Identity not found';
	        		break;
	        
	        	case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
	        		$this->view->alert = 'Invalid credential';
	        		break;
	        
	        	case Zend_Auth_Result::SUCCESS:
	        		// get user object (ommit password_hash)
	        		$user = $authAdapter->getResultRowObject(null, 'password');
	        		//$user = array_merge($user, array('test' => md5(time()*rand(1,10))));
	        		
	        		
	        		// check if the user is approved
	        		
        			// to help thwart session fixation/hijacking
	        			if ($form->getValue('rememberMe') == 1) {
	        				// remember the session for 604800s = 7 days
	        				Zend_Session::rememberMe(604800);
	        			} else {
	        				// do not remember the session
	        				Zend_Session::forgetMe();
	        			}
        			// store user object in the session
        			$authStorage = Zend_Auth::getInstance()->getStorage();
        			$authStorage->write($user);
        			//$authStorage->write(array('test' => md5(time()*rand(1,10))));
        			$this->_redirect('index');
	        		
	        		break;
	        
	        	default:
	        		$this->view->alert = 'Wrong username and/or password';
	        		break;
	        }

	      }
	    }
	    
	    $providerAuth = Zend_Tbs_Auth::getInstance();
	     
	    $providers = $providerAuth->getIdentity();
	    //var_dump($providers);
	    // Here the response of the providers are registered
	    if ($this->_hasParam('provider')) {
	    	$provider = $this->_getParam('provider');
	    	 
	    	switch ($provider) {
	    		case "facebook":
	    			if ($this->_hasParam('code')) {
	    				$adapter = new Zend_Tbs_Auth_Adapter_Facebook(
	    						$this->_getParam('code'));
	    				$result = $providerAuth->authenticate($adapter);
	    			}
	    			if($this->_hasParam('error')) {
	    				throw new Zend_Controller_Action_Exception('Facebook login failed, response is: ' .
	    						$this->_getParam('error'));
	    			}
	    			break;
	    		case "google":
	    			 
	    			if ($this->_hasParam('code')) {
	    				$adapter = new Zend_Tbs_Auth_Adapter_Google(
	    						$this->_getParam('code'));
	    				$result = $providerAuth->authenticate($adapter);
	    			}
	    			if($this->_hasParam('error')) {
	    				throw new Zend_Controller_Action_Exception('Google login failed, response is: ' .
	    						$this->_getParam('error'));
	    			}
	    			break;
	    			 
	    	}
	    	// What to do when invalid
	    	if (isset($result) && !$result->isValid()) {
	    		$providerAuth->clearIdentity($this->_getParam('provider'));
	    		throw new Zend_Controller_Action_Exception('Login failed');
	    	} else {
	    		//check if the extern_connect mail is in the user table
	    		$extern_connect = $providerAuth->getIdentity();
	    		$cprofil = null;
	    		foreach ($extern_connect as $a){
		    		switch ($a->getName()) {
		    			case 'facebook':
		    				$cprofil = new Application_Model_Profil_Facebook($a);
		    				break;
		    			case 'google':
		    				$cprofil = new Application_Model_Profil_Google($a);
		    				break;
		    		}
	    		}
	    		$userMapper = new Application_Model_UserMapper();
	    		//construct a $user from table
	    		$userlist = $userMapper->fetchAll(array('email = ?' => $cprofil->getEmail()));
	    		
	    		if($userlist){
	    			
	    			$thisuser = $userlist[0];
	    			$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter());
	    			$authAdapter->setTableName('user')
	    			->setIdentityColumn('email')
	    			->setCredentialColumn('password')
	    			->setCredentialTreatment('?')
	    			->setIdentity($thisuser->getEmail())
	    			->setCredential($thisuser->getPassword());
	    			// try to authenticate a user
	    			$result = $authAdapter->authenticate();
	    			// get user object (ommit password_hash)
	    			$thisuser = $authAdapter->getResultRowObject(null, 'password');
	    			
	    			// store user object in the session
	    			$authStorage = Zend_Auth::getInstance()->getStorage();
	    			$authStorage->write($thisuser);
	    			$this->_redirect('index');
	    		}else{
	    			$gender = array( 'male' => 1, 'female' => 2);
	    			//add new user un table with mail last_name first_name gender local provider from $extern_connect
	    			$user = new Application_Model_User();
	    			$user->setAvatar(($cprofil->getGender() ? "p_".$gender[$cprofil->getGender()].".png" : "p_1.png"));
	    			$user->setEmail($cprofil->getEmail());
	    			$user->setFirstName($cprofil->getFirstName());
	    			$user->setLastName($cprofil->getLastName());
	    			$user->setSex(($cprofil->getGender() ? $gender[$cprofil->getGender()] : ''));
	    			$user->setCountry($cprofil->getLocale());
	    			
	    			$userMapper->save($user);
	    			
	    			$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter());
	    			$authAdapter->setTableName('user')
	    			->setIdentityColumn('email')
	    			->setCredentialColumn('password')
	    			->setCredentialTreatment('SHA1(?)')
	    			->setIdentity($cprofil->getEmail())
	    			->setCredential('');
	    			$result = $authAdapter->authenticate();
	    			$user = $authAdapter->getResultRowObject(null, 'password');
	    			// store user object in the session
	    			$authStorage = Zend_Auth::getInstance()->getStorage();
	    			$authStorage->write($user);
	    			$this->_redirect('index');
	    		}
	    
	    
	    		//$this->_redirect('index');
	    
	    		//send mail with mail and password generated for the user
	    		//connect the user
	    		//redirect to index
	    
	    	}
	    }
	    // Normal login page
	    $this->view->googleAuthUrl = Zend_Tbs_Auth_Adapter_Google::getAuthorizationUrl();
	    $this->view->facebookAuthUrl = Zend_Tbs_Auth_Adapter_Facebook::getAuthorizationUrl();
	    
	    $this->render ( 'index' );
	  }
	 
	  
	  public function logoutAction() {
	  	Zend_Tbs_Auth::getInstance()->clearIdentity();
	    Zend_Auth::getInstance ()->clearIdentity ();
	    $this->_redirect('myobjects');
	  }
 
}